const likelesson = document.querySelector('.like-lesson');
const likecomments = document.querySelectorAll('.like-comment');
const commentlikes = document.querySelectorAll('.comment-likes');
let i = 0;
let checked = "✔";

//发送点赞请求
function sendlike(target) {
    let XHR = new XMLHttpRequest();
    let FD = new FormData(target);
    XHR.addEventListener("load", function (event) {
        obj = JSON.parse(event.target.responseText);
        target.previousElementSibling.textContent = obj['likes'];
    });
    XHR.addEventListener("error", function (event) {
        alert("哎呀，数据传输失败了！请检查网络连接，并尝试重载本页面。");
    });
    XHR.open("POST", "/like/");
    XHR.send(FD);
}

//给评论点赞
for (i = 0; i < likecomments.length; i++) {
    if (localStorage.getItem('btn' + likecomments[i].children[2].value)) {
        likecomments[i].children[3].setAttribute('disabled', true);
        likecomments[i].children[3].value = checked;
        continue;
    }
    likecomments[i].addEventListener('submit', function (event) {
        event.preventDefault();
        sendlike(event.target);
        event.target.children[3].value = checked;
        event.target.children[3].setAttribute('disabled', true);
        localStorage.setItem('btn' + event.target.children[2].value, true);
    });
}

//给课程点赞
if (localStorage.getItem('lesson' + likelesson.children[2].value)) {
    likelesson.children[3].setAttribute('disabled', true);
    likelesson.children[3].value = checked;
}
else {
    likelesson.addEventListener('submit', function (event) {
        event.preventDefault();
        sendlike(event.target);
        event.target.children[3].value = checked;
        event.target.children[3].setAttribute('disabled', true);
        localStorage.setItem('lesson' + event.target.children[2].value, true);
    });
}